<template>
    <el-table
        ref="tableRef"
        :data="tableData"
        v-bind="tableDefaultAttribute"
        row-key="id"
        :max-height="tableHeight"
        table-layout="auto"
        @cell-dblclick="update"
        @sort-change="handleSortChange"
    >
        <template #empty>
            <span>无数据</span>
        </template>
        <el-table-column type="selection" width="55" :align="'center'" />
        <template v-for="col in tableColumns" :key="col.prop">
            <el-table-column
                v-if="!col.isHidden"
                :align="col.align"
                :prop="col.prop"
                :label="col.label"
                :fixed="col.fixed"
                :formatter="col.formatter"
                :type="col.type"
                :width="col.width"
            >
                
            </el-table-column>
        </template>
    </el-table>
    <el-button-group class="bg">
        <el-button class="btn" type="primary" :icon="Plus" @click="add"
            >增加</el-button
        >
        <el-button class="btn" type="primary" :icon="Delete" @click="onDelete"
            >删除</el-button
        >
        <el-button class="btn" type="primary" :icon="Search" @click="onQuery"
            >查询</el-button
        >
        <el-button class="btn" type="primary" :icon="Search" @click="onBack"
            >退款</el-button
        >
        <el-button class="btn" type="primary" :icon="Search" @click="onChangePay"
            >转实收付</el-button
        >
    </el-button-group>
    <div class="page">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[50, 100, 150, 200]"
            layout="sizes, prev, pager, next"
            :total="totalnum"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
    <el-dialog
        v-model="dialogUpdateVisible"
        title="预付款维护"
        draggable
        destroy-on-close
        :center="true"
    >
        <PrePay
            :data="paramData"
            @create="onAdded"
            @update="onUpdated"
            @close="onCloseDialog"
        >
        </PrePay>
    </el-dialog>
    <el-dialog
        v-model="dialogQueryVisible"
        title="预付款查询"
        draggable
        destroy-on-close
    >
        <QueryForm
            :queryItems="queryItems"
            @yh-closedialog="onCloseDialog"
        ></QueryForm>
    </el-dialog>
</template>
<script setup lang="ts" name="PrePays">
import { ref, reactive, onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import { ElMessage, ElMessageBox, ElTable } from 'element-plus';
import { Delete, Plus, Search } from '@element-plus/icons-vue';
import {
    isEmpty,
    forEach,
    forEachRight,
    includes,
    findIndex,
    omit,
} from 'lodash';

import type { PrePayModel } from '@/common/types/business';
import {
    tableDefaultAttribute,
    useTableInfo,
    tableColumnDefault,
} from '@/hooks/useTable';
import type { QueryItem, TableColumn } from '@/common/types/app';
import { Request } from '@/app/request';
import {
    initObjectProperty,    
    pickQueryFromTable,
    transFormatter,
    formatDate,
} from '@/common/tools';
import { tableMaxHeightAdjust } from '@/common/const';
import { useAppStore } from '@/store/app';
import PrePay from './PrePay.vue';
const {
    currency,
    client,
    category,
    SelectOptionFeeInOut,
    
    cntrOwner,
} = storeToRefs(useAppStore());
const tableRef = ref<InstanceType<typeof ElTable>>();
const tableData = ref<Array<PrePayModel>>([]);
const paramData = reactive<PrePayModel>({});
const tableHeight = ref(100);

const onFormatter = (_row: any, column: any, cellValue: any) => {
    let data: { value: string | number; label: string }[];
    if (column['property'] === 'currency_cod') {
        data = currency.value;
    } else if (column['property'] === 'fee_unit_cod') {
        data = client.value;
    } else if (column['property'] === 'pay_typ') {
        data = category.value;
    } else if (column['property'] === 'fee_in_out') {
        data = SelectOptionFeeInOut.value;
    } else if (column['property'] === 'fee_owner') {
        data = cntrOwner.value;
    } else {
        return cellValue;
    }

    return transFormatter(cellValue, data);
};

const tableColumns = reactive<TableColumn[]>([
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'fee_unit_cod',
        label: '客户',
        formatter: onFormatter,
        fixed: 'left',
        sortable: 'custom',
        formFieldItemType: 'single',
        optionalValues: client.value,
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 4,
        prop: 'fee_tim',
        label: '付款日期',
        fixed: 'left',
        formatter: formatDate,
        sortable: 'custom',
        formFieldItemType: 'date',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 5,
        prop: 'pay_typ',
        label: '资金账号',
        formatter: onFormatter,
        fixed: 'left',
        sortable: 'custom',
        formFieldItemType: 'single',
        optionalValues: category.value,
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 3,
        prop: 'currency_cod',
        label: '货币',

        sortable: 'custom',
        formFieldItemType: 'single',
        optionalValues: currency.value,
        width: 100,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'amount',

        label: '金额',
        sortable: 'custom',
        width: 150,
    },

    {
        ...tableColumnDefault,
        order: 6,
        prop: 'fee_in_out',
        label: '收付款类型',
        formatter: onFormatter,
        sortable: 'custom',
        formFieldItemType: 'single',
        optionalValues: SelectOptionFeeInOut.value,
        width: 120,
    },
    {
        ...tableColumnDefault,
        order: 12,
        prop: 'fee_owner',
        label: '成本中心',
        formatter: onFormatter,
        sortable: 'custom',
        formFieldItemType: 'single',
        optionalValues: cntrOwner.value,
        width: 150,
    },
    

    {
        ...tableColumnDefault,
        order: 8,
        prop: 'pay_no',
        label: '付款码',
        sortable: 'custom',
        formFieldItemType: 'input',
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 14,
        prop: 'remark',
        label: '备注',
        sortable: 'custom',
        width: 200,
    },
]);



const dialogQueryVisible = ref(false);
const dialogUpdateVisible = ref(false);
let queryWhere = {};

const onRefresh = async () => {
    // console.log('参数', paramData);

    const req = new Request('预付款查询', {
        skip: (currentPage.value - 1) * pageSize.value,
        take: pageSize.value,
        order: orders,
        ...queryWhere,
    });
    const r = await req.post();

    totalnum.value = r.ext;
    tableData.value.length = 0;

    if (!isEmpty(r.obj)) {
        tableData.value = r.obj;
    }
};
const {
    currentPage,
    orders,
    pageSize,
    totalnum,
    handleSizeChange,
    handleCurrentChange,
    handleSortChange,
} = useTableInfo(onRefresh);
onMounted(() => {
    // onRefresh();
    tableHeight.value =
        window.innerHeight -
        Math.ceil(tableRef.value?.$el.getBoundingClientRect().bottom) +
        tableMaxHeightAdjust;
    // alert(tableHeight.value);
});
const add = () => {
    initObjectProperty(paramData);
    dialogUpdateVisible.value = true;
};
const update = (row: any) => {
    Object.assign(paramData, row);
    dialogUpdateVisible.value = true;
};
const onAdded = (data: PrePayModel) => {
    tableData.value.unshift(data);
};
const onUpdated = (data: PrePayModel) => {
    const i = findIndex(tableData.value, (o) => {
        return o.id === data.id;
    });
    if (i > -1) {
        Object.assign(tableData.value[i], omit(data, ['id']));
    } else {
        ElMessage.error('修改失败');
    }
};
const onCloseDialog = async (arg?: any) => {
    if (dialogUpdateVisible.value) {
        dialogUpdateVisible.value = false;
    }
    if (dialogQueryVisible.value) {
        // 查询
        currentPage.value = 1;
        queryWhere = arg;
        onRefresh();

        dialogQueryVisible.value = false;
    }
};
const getSelectionIds = (): number[] => {
    const rows: Array<PrePayModel> = tableRef.value?.getSelectionRows() || [];
    if (rows.length === 0) {
        ElMessage.info({
            message: '请选择预付款',
        });
        return [];
    }
    const ids = Array<number>();
    forEach(rows, (v: PrePayModel) => {
        ids.push(v.id as number);
    });
    return ids;
}
const onDelete = async () => {
    
    const ids = getSelectionIds();
    if (ids.length === 0) {
        return;
    }

    const msg = '';
    // const delids = ids.join(',');
    const cr = await ElMessageBox.confirm(msg, '确认删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return true;
        })
        .catch(() => {
            return false;
        });
    if (cr) {
        //
        const req = new Request('预付款删除', { ids });
        const r = await req.post();
        if (r.code > 100) {
            forEachRight(tableData.value, (v: PrePayModel, i: number) => {
                if (includes(ids, v.id)) {
                    tableData.value.splice(i, 1);
                }
            });
        }
    }
};
const onBack = async () => {
    const ids = getSelectionIds();
    if (ids.length === 0) {
        return;
    }

    const msg = '';
    // const delids = ids.join(',');
    const cr = await ElMessageBox.confirm(msg, '确认退款', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return true;
        })
        .catch(() => {
            return false;
        });
    if (cr) {
        //
        const req = new Request('预付款退款', { ids });
        const r = await req.post();
        if (r.code > 100) {
            onRefresh();
        }
    }
}
const onChangePay = async () => {
    const ids = getSelectionIds();
    if (ids.length === 0) {
        return;
    }

    const msg = '';
    // const delids = ids.join(',');
    const cr = await ElMessageBox.confirm(msg, '确认转实付款', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return true;
        })
        .catch(() => {
            return false;
        });
    if (cr) {
        //
        const req = new Request('预付款转实付款', { ids });
        const r = await req.post();
        if (r.code > 100) {
            onRefresh();
        }
    }
}
const onQuery = () => {
    dialogQueryVisible.value = true;
};
const queryItems: Array<QueryItem> = pickQueryFromTable(tableColumns);
</script>
<style lang="scss" scoped>
.bg {
    margin-top: 10px;

    .btn {
        margin-right: 10px;
    }
}

.page {
    float: right;
    margin-top: 10px;
}
</style>
